//
//  ProfileVC.swift
//  Employee
//
//  Created by swordjoy on 2017/3/13.
//  Copyright © 2017年 remotevillage. All rights reserved.
//

import UIKit
import RxSwift
import SwiftyJSON

class ProfileVC: BaseVC {
  
  fileprivate var titles: [String] = []
  
  fileprivate var headerV: EmployeeInfoV!
  fileprivate var tableView: UITableView!
  fileprivate var logoutButton: UIButton!
  
  fileprivate var selectImageV: SelectImagePopV!
  
  override func viewDidLoad() {
    
    super.viewDidLoad()
    view.backgroundColor = GlobalConfig.BGWhiteColor
    
    titles = ["社区切换","意见与反馈","关于世外物业"]
    
    create()
    closure()
    
    NotificationCenter.default.addObserver(self, selector: #selector(change), name: NSNotification.Name.changeCompany.changeCompanyUpdateData, object: nil)
    
    
    
  }
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    @objc fileprivate func change() {
        self.headerV.update()
        self.tableView.reloadData()
    }
    
    
  override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    navigationController?.setNavigationBarHidden(false, animated: true)
    navigationController?.navigationBar.setBackgroundImage(GlobalConfig.BGSkyBlueImage, for: .default)
    GlobalConfig.baiduStatisticsPageViewStart("我的")
  }
  
  override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)
    
    GlobalConfig.baiduStatisticsPageViewEnd("我的")
  }
  
  override var preferredStatusBarStyle: UIStatusBarStyle {
    return .lightContent
  }
  
}

// MARK: - action
extension ProfileVC {
  
  fileprivate func closure() {
    
    headerV.editHeadIconClosure = { [unowned self] in
      self.selectImageV.show(in: self.navigationController!.view)
    }
    
    headerV.headIconClickClosure = { [unowned self] (imageView) in
        let image = SJImageModel(thumb: imageView, thumb: imageView.image, original: User.avatar)
        let vc = ImageViewer(images: [image], presentingVC: self)
        vc.show(index: 0)
    }
    
    selectImageV.takePhotoClosure = { [unowned self] in
      self.takePhoto()
    }
    
    selectImageV.selectClosure = { [unowned self] in
        let avatatPicker = AvatarPicker()
        avatatPicker.delegate = self
        self.navigationController?.pushViewController(avatatPicker, animated: true)
    }
    
  }
  
  
    @objc fileprivate func logoutAction() {
        let tipV = TipPopV(frame: UIScreen.main.bounds, type: .logout)
        // closure
        tipV.confirmClosure = {
            SJApp.showHUD()
            let _ = UserRequest.shared.logout(success: {
               // let error = EMClient.shared().logout(true)
               // if let temp = error {
                //    SJApp.log("环信错误: \(temp.errorDescription)")
               //     SJHint.show("退出登录失败,请重新尝试")
               // }
               // else {
                    let longinVC = LoginVC()
                    GlobalConfig.notificationCenter.post(name: Notification.Name.updateHome.updateHomeToDefaultWhenLogout, object: nil)
                    let loginNav = SJHiddenNavigationC(rootViewController: longinVC)
                    SJApp.keyWindow.rootViewController?.present(loginNav, animated: true, completion: {
                        runOnMainThread {
                            self.navigationController?.popToRootViewController(animated: false)
                        }
                        Account.isLogin = false
                        JPUSHService.setTags(Set(), alias: "", fetchCompletionHandle: nil)
                        SJCache.clearAll()
                        self.headerV.headImage = nil
                    })
               // }
            }, failure: {
                SJHint.show("退出登录失败,请重新尝试")
            })
        }

        tipV.show(in: navigationController!.view)
    }
  
}

// MARK: - AvatarPickerDelegate
extension ProfileVC: AvatarPickerDelegate {
    func avatarPickerDidFinishSelected(with avatar: UIImage?) {
        guard let temp = avatar else {
            SJHint.show("获取图片失败,请重新选择")
            return
        }
        
        SJApp.showHUD()
        let _ = FileRequest.shared.uploadHeadIcon(imageData: temp.uploadData, success: {  (model) in
            
//            // 保存用户信息
//            let newData = NSMutableDictionary.init(dictionary: User.userInfoDic!)
//
//            newData["useravatar"] = model.headImage//
//
//            User.save(with: JSON.init(newData))
            User.headImageData = UIImageJPEGRepresentation(temp, 1.0)
            User.avatar = model.headImage
            runOnMainThread {
                self.headerV.headImage = temp
            }
        }) { 
            // 头像图片上传失败
        }
    }
}

// MARK: - fileprivate
extension ProfileVC {
  
    fileprivate func updateData() {
        self.headerV.update()
    }
  
    fileprivate func takePhoto() {
        let imagePicker = UIImagePickerController()
        imagePicker.delegate = self
        imagePicker.allowsEditing = true
        imagePicker.sourceType = .camera
        self.present(imagePicker, animated: true, completion: nil)
    }
  
  fileprivate func create() {
    addBackItem(color: .white)
    
    headerV = EmployeeInfoV(frame: CGRect(x: 0, y: 0, width: UIScreen.width, height: 260))
    
    tableView = UITableView(frame: CGRect(x: 0, y: 0, width: UIScreen.width, height: UIScreen.height - 60))
    tableView.backgroundColor = UIColor.clear
    tableView.delegate = self
    tableView.dataSource = self
    tableView.separatorStyle = .none
    tableView.tableHeaderView = headerV
    tableView.register(ProfileCell.self, forCellReuseIdentifier: ProfileCell.identifier)
    tableView.sectionHeaderHeight = 10
    tableView.rowHeight = ProfileCell.height
    view.addSubview(tableView)
    
    let footer = UIView(frame: CGRectMake(0, 0, UIScreen.width, 75))
    //footer.backgroundColor =
    
    logoutButton = UIButton()
    footer.addSubview(logoutButton)
    logoutButton.backgroundColor = UIColor.white
    logoutButton.setTitle("退出登录", for: .normal)
    logoutButton.setTitleColor(GlobalConfig.GrapeFruitColor, for: .normal)
    logoutButton.addTarget(self, action: #selector(logoutAction), for: .touchUpInside)
    logoutButton.snp.makeConstraints { (make) in
      make.left.equalTo(10)
      make.right.equalTo(-10)
      make.top.equalTo(5)
      make.height.equalTo(50)
    }
    
    tableView.tableFooterView = footer
    
    selectImageV = SelectImagePopV(frame: UIScreen.main.bounds)
    
  }

}

// MARK: - UIImagePickerControllerDelegate, UINavigationControllerDelegate

extension ProfileVC: UIImagePickerControllerDelegate, UINavigationControllerDelegate {

    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        guard let image = info[UIImagePickerControllerOriginalImage] as? UIImage else {
            return
        }

        SJApp.showHUD()
        let _ = FileRequest.shared.uploadHeadIcon(imageData: image.uploadData, success: { (model) in
             User.headImageData = UIImageJPEGRepresentation(image, 1.0)
            User.avatar = model.headImage
            runOnMainThread {
                self.headerV.headImage = image
            }
        }) {
        
        }

        picker.dismiss(animated: true) { }
    }
  
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        picker.dismiss(animated: true) { }
    }
  
}

// MARK: - UITableViewDataSource

extension ProfileVC : UITableViewDataSource {
  
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return titles.count
    }
  
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: ProfileCell.identifier) as! ProfileCell
        cell.title = titles[indexPath.row]
        cell.tip = indexPath.row == 0 ? User.communityName : ""
        return cell
    }
}

// MARK: - UITableViewDelegate

extension ProfileVC : UITableViewDelegate {
  
  func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    
    switch indexPath.row {
    case 0:
        let vc = CommunityChangeVC()
        navigationController?.pushViewController(vc, animated: true)
    case 1:
      let vc = FeedbackVC()
      navigationController?.pushViewController(vc, animated: true)
    case 2:
      let vc = AboutVC()
      navigationController?.pushViewController(vc, animated: true)
    default: break
    }
    
    tableView.deselectRow(at: indexPath, animated: true)
  }
  
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {

        let view = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.width, height: 10))
        view.backgroundColor = UIColor.clear
        return view

    }
}

